$(function(){
	loadDesktopByTab();//加载所有数据
	gotoDesktop(Desktops["desktop_1"]);//转入第一个桌面
});

var Desktops = {};
var ATTR = {
	desktopIsMoving: false,
	curDesktop: null
};

/**
 * 创建桌面，加载应用，绑定模块标签.
 */
function loadDesktopByTab(){
	for(var tabId in tab2Desktop){
		var desktopId = tab2Desktop[tabId];
		var desktop = createDesktop(desktopId);
		
		desktop.tabId = tabId;
		$(desktop).bind("turnleave", function(event){
			var _desktop = event.target;
			$("#"+_desktop.tabId).removeClass("tab-current");
		});
		$(desktop).bind("turninto", function(event){
			var _desktop = event.target;
			$("#"+_desktop.tabId).addClass("tab-current");
			ATTR.curDesktop= _desktop;
		});
		$(desktop).bind("finishturninto", function(event){
			ATTR.desktopIsMoving = false;
		});
		
		$("#"+tabId).bind("click", function(event){
			var _tab = event.target;
			gotoDesktop(Desktops[tab2Desktop[$(_tab).attr("id")]]);
		});
		
		Desktops[desktopId] = desktop;
	}
	
}

function createDesktop(dskId){
	var desktop = new Desktop(dskId);
	$(desktop).triggerHandler('load',[$("#desktopContainer")]);
	var appIds = desktopsData[dskId];
	for(var i in appIds){
		var app = new App(appIds[i], appsData[appIds[i]]);
		$(app).bind("beforefocus", function(event){
			gotoDesktop(desktop, event);
			$("#taskItemBox").find(".task-item-current").removeClass("task-item-current");
		});
		desktop.loadapp(app);
	}
	return desktop;
}

function gotoDesktop(desktop, event){
	if(ATTR.desktopIsMoving)return;
	if(!desktop.isCurrent()){
		if(ATTR.desktopIsMoving)return;
		ATTR.desktopIsMoving = true;
	    if(ATTR.curDesktop)ATTR.curDesktop.turnleave();
	    desktop.turninto(event);
	}
}
	